//
//  AppDelegate.m
//  HTP
//
//  Created by admin on 15/10/25.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "AppDelegate.h"
#import "AppdelegateLoginVC.h"
#import "RootViewController.h"
#import "BaseNavigationViewController.h"

#import "LeftSortsViewController.h"

#import "HomePageViewController.h"

#import "System_config.h"
#import "UIAlertView+Block.h"

#import <AlipaySDK/AlipaySDK.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
@interface AppDelegate () <BMKGeneralDelegate>

@property (nonatomic,retain) LeftSortsViewController *leftVC;
//百度地图主引擎
@property (nonatomic,retain) BMKMapManager *mapManager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //本地数据库相关
    int version_info = 2;//需要删除本地数据库+1
    [self deleteCoreDataByVersion:version_info];
    [XLCoreDataManager setupCoreDataStackWithStoreNamed:@"HTP.sqlite"];
    
    
    _mapManager = [[BMKMapManager alloc] init];
    //百度地图鉴权
    if ([_mapManager start:@"pnFz8VfXQ7G7jL8IeZ3EqRrB" generalDelegate:self]) {
        NSLog(@"鉴权成功");
    }else
        NSLog(@"鉴权失败");
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.window = [[UIWindow alloc] initWithFrame:APPBounds];
    //延迟启动页面的加载时间
    [NSThread sleepForTimeInterval:1.0];
    
    [self.window makeKeyAndVisible];
    if(!USERCONTENT.isLoginUser){
        [self changeLoginVc];
    } else{
        [self changeRootVc];
    }
    // Override point for customization after application launch.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserLogin:) name:GETUSERLOGIN object:nil];
    return YES;
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
   
    //如果是支付宝返回
    if ([sourceApplication isEqualToString:@"com.alipay.iphoneclient"]) {
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSString *stringResult = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
                if ([stringResult isEqualToString:@"9000"]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:@"支付成功!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alert show];
                }else{
                    NSString *erString = [NSString stringWithFormat:@"支付失败!请重试或者联系客服!"];
                    if ([stringResult isEqualToString:@"6001"]) {
                        erString = [NSString stringWithFormat:@"用户中途取消123123"];
                    }else if([stringResult isEqualToString:@"6002"]) {
                        erString = [NSString stringWithFormat:@"网络连接出错"];
                    }
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:erString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }];
        }
        if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
            [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSString *stringResult = [NSString stringWithFormat:@"%@",[resultDic objectForKey:@"resultStatus"]];
                if ([stringResult isEqualToString:@"9000"]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:@"支付成功!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alert show];
                }else{
                    NSString *erString = [NSString stringWithFormat:@"支付失败!请重试或者联系客服!"];
                    if ([stringResult isEqualToString:@"6001"]) {
                        erString = [NSString stringWithFormat:@"用户中途取消"];
                    }else if([stringResult isEqualToString:@"6002"]) {
                        erString = [NSString stringWithFormat:@"网络连接出错"];
                    }
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付宝支付结果" message:erString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }];
        }
    }
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
//    [self saveContext];
}
- (void)deleteCoreDataByVersion:(int)version_info{
    if ([USERCONTENT isNeedDeleteCoreData:version_info]) {
        [XLCoreDataManager deleteContext];
    }
}
//TODO:更改rootView
/**
 *  跳转到登录界面登录界面
 */
-(void)changeRootVc{
    RootViewController *mainVC      = [[RootViewController alloc] init];
    self.mainNavigationController   = [[BaseNavigationViewController alloc] initWithRootViewController:mainVC];
    _leftVC = [[LeftSortsViewController alloc] init];
    self.LeftSlideVC                = [[LeftSlideViewController alloc] initWithLeftView:_leftVC andMainView:self.mainNavigationController];
    self.window.rootViewController  =  self.LeftSlideVC;
    self.LeftSlideVC.closed = YES;
}
-(void)changeLoginVc{
    HomePageViewController *homeVc = [[HomePageViewController alloc] init];
    UINavigationController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:homeVc];
    self.window.rootViewController = nav;
}
//TODO:用户唤醒登录状态
-(void)getUserLogin:(NSNotification *)notification{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"青苗家教" message:@"登入您的帐号" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:@"取消", nil];
    [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            BaseViewController *base = (BaseViewController *)notification.object;
            AppdelegateLoginVC *login = [[AppdelegateLoginVC alloc] init];
            login.baseVC = base;
            [self.window.rootViewController presentViewController:login animated:YES completion:^{
        
            }];
        }
    }];
}
@end
